package com.guomei.controller.curse;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.guomei.utils.PageData;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guomei.bean.User;
import com.guomei.bean.curse.Course;
import com.guomei.bean.curse.domain.UserDistributorCourseRel;
import com.guomei.bean.curse.vo.UserDistributorCourseRelDTO;
import com.guomei.bean.curse.vo.UserDistributorCourseRelVo;
import com.guomei.mapper.UserMapper;
import com.guomei.mapper.curse.CourseMapper;
import com.guomei.mapper.curse.UserDistributorCourseRelMapper;
import com.guomei.utils.Result;

import lombok.extern.slf4j.Slf4j;

/**
 * 用户-招生老师-课程关系Controller
 */
@RestController
@RequestMapping("/api1/userDistributorCourseRel")
@Slf4j
public class UserDistributorCourseRelController {
    
    @Resource
    UserDistributorCourseRelMapper userDistributorCourseRelMapper;

    @Resource
    CourseMapper courseMapper;

    @Resource
    UserMapper userMapper;

    /**
     * 查询用户-招生老师-课程关系
     */
    @PostMapping("/select")
    public Result<?> select(@RequestBody UserDistributorCourseRelDTO dto) {
        QueryWrapper<UserDistributorCourseRel> wrapper = new QueryWrapper<>();

        if (dto.getStudentId() != null) {
            wrapper.eq("student_id", dto.getStudentId());
        }

        if (dto.getDistributorId() != null) {
            wrapper.eq("distributor_id", dto.getDistributorId());
        }

        if (dto.getCourseId() != null) {
            wrapper.eq("course_id", dto.getCourseId());
        }

        if (dto.getStatus() != null) {
            wrapper.eq("status", dto.getStatus());
        }

        if (dto.getIds() != null) {
            wrapper.in("id", dto.getIds());
        }

        List<UserDistributorCourseRel> items = userDistributorCourseRelMapper.selectList(wrapper);
        List<UserDistributorCourseRelVo> vos = new ArrayList<>();
        List<Long> courseIds = new ArrayList<>();
        List<Long> studentIds = new ArrayList<>();
        List<Long> distributorIds = new ArrayList<>();
        
        for (UserDistributorCourseRel item : items) {
            UserDistributorCourseRelVo vo = new UserDistributorCourseRelVo();
            vo.setId(item.getId());
            vo.setStudentId(item.getStudentId());
            vo.setDistributorId(item.getDistributorId());
            vo.setCourseId(item.getCourseId());
            vo.setOrderId(item.getOrderId());
            vo.setDistributionRatio(item.getDistributionRatio());
            vo.setStatus(item.getStatus());
            vo.setCreatedTime(item.getCreatedTime());
            vo.setUpdatedTime(item.getUpdatedTime());
            
            courseIds.add(item.getCourseId());
            studentIds.add(item.getStudentId());
            distributorIds.add(item.getDistributorId());
            vos.add(vo);
        }

        // 查询课程信息
        List<Course> courses = new ArrayList<>();
        if (!courseIds.isEmpty()) {
            courses = courseMapper.selectByIds(courseIds);
        }
        java.util.Map<Long, Course> courseById = new java.util.HashMap<>();
        for (Course c : courses) {
            if (c != null && c.getId() != null) {
                courseById.put(c.getId(), c);
            }
        }

        // 查询用户信息（学生和招生老师）
        List<User> users = new ArrayList<>();
        if (!studentIds.isEmpty()) {
            users.addAll(userMapper.selectByAll(studentIds));
        }
        if (!distributorIds.isEmpty()) {
            users.addAll(userMapper.selectByAll(distributorIds));
        }
        java.util.Map<Long, User> userById = new java.util.HashMap<>();
        for (User u : users) {
            if (u != null && u.getId() != null) {
                userById.put(u.getId(), u);
            }
        }

        // 设置关联信息
        for (UserDistributorCourseRelVo vo : vos) {
            vo.setCourse(courseById.get(vo.getCourseId()));
            vo.setStudent(userById.get(vo.getStudentId()));
            vo.setDistributor(userById.get(vo.getDistributorId()));
        }

        PageData<UserDistributorCourseRelVo> data = new PageData<>();
        data.setData(vos);
        data.setTotal((long) items.size());
        data.setPageNum(dto.getPageNum());
        data.setPageSize(dto.getPageSize());

        return Result.success(data);
    }

    /**
     * 保存用户-招生老师-课程关系
     */
    @PostMapping("/save")
    public Result<?> save(@RequestBody UserDistributorCourseRel rel) {
        if (rel.getId() != null) {
            // 更新
            userDistributorCourseRelMapper.updateById(rel);
            return Result.success(rel);
        }

        // 检查是否已存在相同的关系
        UserDistributorCourseRel existing = userDistributorCourseRelMapper.selectByStudentDistributorAndCourse(
            rel.getStudentId(), rel.getDistributorId(), rel.getCourseId());
        
        if (existing != null) {
            return Result.error("该关系已存在");
        }

        userDistributorCourseRelMapper.insert(rel);
        return Result.success(rel);
    }

    /**
     * 批量删除用户-招生老师-课程关系
     */
    @DeleteMapping("/dropByIds")
    public Result<?> dropByIds(@RequestBody List<Long> ids) {
        userDistributorCourseRelMapper.deleteBatchIds(ids);
        return Result.success();
    }

    /**
     * 根据学生ID查询关系
     */
    @PostMapping("/selectByStudentId")
    public Result<?> selectByStudentId(@RequestBody UserDistributorCourseRelDTO dto) {
        List<UserDistributorCourseRel> items = userDistributorCourseRelMapper.selectByStudentId(dto.getStudentId());
        return Result.success(items);
    }

    /**
     * 根据招生老师ID查询关系
     */
    @PostMapping("/selectByDistributorId")
    public Result<?> selectByDistributorId(@RequestBody UserDistributorCourseRelDTO dto) {
        List<UserDistributorCourseRel> items = userDistributorCourseRelMapper.selectByDistributorId(dto.getDistributorId());
        return Result.success(items);
    }

    /**
     * 根据课程ID查询关系
     */
    @PostMapping("/selectByCourseId")
    public Result<?> selectByCourseId(@RequestBody UserDistributorCourseRelDTO dto) {
        List<UserDistributorCourseRel> items = userDistributorCourseRelMapper.selectByCourseId(dto.getCourseId());
        return Result.success(items);
    }
}
